package com.wy.system.service.impl;

import com.wy.model.entity.User;
import com.wy.system.custom.CustomUser;
import com.wy.system.service.PermissionService;
import com.wy.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserService userService;

  @Autowired
  private PermissionService permissionService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userService.getUserInfoByUserName(username);
    if (user == null){
      throw new UsernameNotFoundException("用户不存在");
    }
    if (user.getStatus().intValue() == 0){
      throw new RuntimeException("用户被禁用了");
    }
    //根据userid查询操作权限数据
    List<String> userButtonList = permissionService.getUserButtonList(user.getId());
    //转换成security要求格式数据
    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
    for (String perm : userButtonList) {
      authorities.add(new SimpleGrantedAuthority(perm.trim()));
    }
    return new CustomUser(user, authorities);
  }
}
